/*
 * Copyright (C) 2012-2013  Romain DUBOIS
 * 
 * This file is part of NeMoS - Network and Modular Software
 * 
 * NeMoS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * NeMoS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with NeMoS.  If not, see <http://www.gnu.org/licenses/>.
 */
package nemos.util;

/**
 * BlockingReference : The blocking reference.
 * 
 * <p>
 * This class is a reference on an object which is not known yet. A call to the
 * {@link #get()} method blocks until the referenced object is known.
 * </p>
 * 
 * @param <T>
 *            The referenced object type
 * 
 * @author Romain DUBOIS
 */
public class BlockingReference<T> {

    /** The referenced object */
    private T mReferenced;
    /** The set flag */
    private boolean mSet;

    /**
     * Constructor.
     */
    public BlockingReference() {
        super();
        mSet = false;
    }

    /**
     * Get the referenced value. This is a blocking method.
     * 
     * @return The referenced value
     * @throws InterruptedException
     *             If thread has been interrupted before referenced object is
     *             known
     */
    public T get() throws InterruptedException {
        synchronized (this) {
            while (!mSet) {
                this.wait();
            }
        }
        return mReferenced;
    }

    /**
     * Set the referenced object.
     * 
     * @param pReferenced
     *            The referenced object to set
     */
    public void set(final T pReferenced) {
        synchronized (this) {
            mSet = true;
            mReferenced = pReferenced;
            this.notifyAll();
        }
    }
}
